package controllers

import (
	"book_manage/models"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"strconv"
	"strings"
)

type OrdersController struct {
	beego.Controller
}

func (c *OrdersController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Methods", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Headers", "*")
	if c.Ctx.Input.Method() == "OPTIONS" {
		c.Ctx.Output.SetStatus(200)
		c.StopRun()
	}
	OrdersKeys := models.Rdb.Keys(models.Ctx, "order:*").Val()
	//fmt.Println(OrdersKeys)
	var orders []models.Ret_Order
	for _, k := range OrdersKeys {
		var order models.Ret_Order
		o, _ := models.Rdb.HGetAll(models.Ctx, k).Result()
		//fmt.Println(o)
		order.Condition = o["Condition"]
		order.CreatedAt = o["CreatedAt"]
		s := o["student_id"]
		b := o["book_id"]
		order.StudentId = s
		order.BookId = b
		order.ID = k
		order.StudentName, _ = models.Rdb.Get(models.Ctx, fmt.Sprintf("student:%s", s)).Result()
		order.BookName, _ = models.Rdb.Get(models.Ctx, fmt.Sprintf("book:%s", b)).Result()
		//fmt.Println(order)
		orders = append(orders, order)
	}
	c.Data["json"] = models.Msg{
		Code: 200,
		Msg:  "获取成功",
		Data: orders,
	}
	c.ServeJSON()
}
func (c *OrdersController) Update() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Methods", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Headers", "*")
	if c.Ctx.Input.Method() == "OPTIONS" {
		c.Ctx.Output.SetStatus(200)
		c.StopRun()
	}
	Id := c.GetString("id")
	if c.Ctx.Input.Method() == "GET" {
		order, _ := models.Rdb.HGetAll(models.Ctx, Id).Result()
		c.Data["json"] = models.Msg{
			Code: 200,
			//Msg:  "",
			Data: models.Ret_Order{
				StudentId: order["student_id"],
				BookId:    order["book_id"],
				Condition: order["Condition"],
				CreatedAt: order["CreatedAt"],
			},
		}
		c.ServeJSON()
		return
	}
	condition := c.GetString("Condition")
	ss := strings.Split(Id, ":")
	id, _ := strconv.Atoi(ss[1])
	fmt.Println(id)
	models.DB.Where("id = ?", id).Updates(&models.Order{Condition: condition})
	models.Rdb.HSet(models.Ctx, Id, "Condition", condition)
	c.Data["json"] = models.Msg{
		Code: 200,
		Msg:  "修改成功",
		Data: nil,
	}
	c.ServeJSON()
}
func (c *OrdersController) Del() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Methods", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Headers", "*")
	if c.Ctx.Input.Method() == "OPTIONS" {
		c.Ctx.Output.SetStatus(200)
		c.StopRun()
	}
	Id := c.GetString("id")
	ss := strings.Split(Id, ":")
	id, _ := strconv.Atoi(ss[1])
	fmt.Println(id)
	models.DB.Where("id = ?", id).Delete(&models.Order{})
	models.Rdb.Del(models.Ctx, "Id")
	c.Data["json"] = models.Msg{
		Code: 200,
		Msg:  "删除成功",
		Data: nil,
	}
	c.ServeJSON()
}
